package banco;

import hibernate.HibernateUtil;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class DAOFactory<Objeto> {

    public void saveOrUpdate(Objeto o) {
        Session sessao = null;
        Transaction tx = null;
        try {
            sessao = HibernateUtil.getSession();
            tx = sessao.beginTransaction();
            sessao.saveOrUpdate(o);
            tx.commit();
        } catch (Exception ex) {
            tx.rollback();
            ex.printStackTrace();
        } finally {
            if (sessao != null) {
                try {
                    sessao.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public void delete(Objeto o) {
        Session sessao = null;
        Transaction tx = null;
        try {
            sessao = HibernateUtil.getSession();
            tx = sessao.beginTransaction();
            sessao.delete(o);
            tx.commit();
        } catch (Exception ex) {
            tx.rollback();
            ex.printStackTrace();
        } finally {
            if (sessao != null) {
                try {
                    sessao.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    public List<Objeto> findAll(String Objeto) {
        Session sessao = null;
        Transaction tx = null;
        try {
            sessao = HibernateUtil.getSession();
            tx = sessao.beginTransaction();
            Query q = sessao.getNamedQuery(Objeto + ".findAll");
            @SuppressWarnings("unchecked")
            List<Objeto> lista = q.list();
            tx.commit();
            return lista;
        } catch (Exception ex) {
            tx.rollback();
            ex.printStackTrace();
            return null;
        } finally {
            if (sessao != null) {
                try {
                    sessao.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
